const bookBack = require('../models/bookBack.js')
const bookFile = require('../models/bookFile.js')
const { bookBackImgType,bookUploadFileType } = require('../config/setting.js')
const fs = require('fs')
const path = require('path')

class BackCtl {
  async find(ctx) {
    let { fields = '', page = 1, perPage = 15 } = ctx.query
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    page = Math.max(page * 1, 1) - 1
    perPage = Math.max(perPage * 1, 1)
    ctx.body = await bookBack.find().select(selectFields).limit(perPage).skip(perPage * page)
  }
  async findById(ctx) {
    const { fields = '' } = ctx.query
    const id = ctx.params.id
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const option = await bookBack.findById(id)
      .select(selectFields)
    ctx.body = option
  }
  async create(ctx) { //添加背景图片
    const file = ctx.request.files.file
    let tf = false
    let suffix
    const paths = path.join(__dirname, '../public/uploads', '/book/back')
    for (const item of bookBackImgType) {
      if (item === file.type) {
        tf = true
        suffix = new RegExp(/(.[^\/]*)$/ig).exec(file.type)[0].replace('/', '')
        break
      }
    }
    if (tf) {
      const baseName = path.basename(file.path)
      const avatarPath = path.resolve(paths, `./${baseName}.${suffix}`)
      const readStream = fs.createReadStream(file.path)
      const writeStream = fs.createWriteStream(avatarPath)
      readStream.pipe(writeStream)
      const url = `${ctx.origin}/uploads/book/back/${baseName}.${suffix}`
      await new bookBack({
        img: url
      }).save()
      ctx.body = { url }
    } else {
      ctx.throw(415, '不支持该类型格式的图片')
    }
  }
  async update(ctx) { //更改背景图片
    const file = ctx.request.files.file
    let tf = false
    let suffix
    const paths = path.join(__dirname, '../public/uploads', '/book/back')
    const img = ctx.state.bookBackOption.img.match(/\/upload_.*/)[0] || ''
    const baseName = path.basename(file.path)
    for (const item of bookBackImgType) {
      if (item === file.type) {
        tf = true
        suffix = new RegExp(/(.[^\/]*)$/ig).exec(file.type)[0].replace('/', '')
        break
      }
    }
    if (tf) {
      fs.unlink(paths + img, async error => {
      })
      const avatarPath = path.resolve(paths, `./${baseName}.${suffix}`)
      const readStream = fs.createReadStream(file.path)
      const writeStream = fs.createWriteStream(avatarPath)
      readStream.pipe(writeStream)
      const url = `${ctx.origin}/uploads/book/back/${baseName}.${suffix}`
      await ctx.state.bookBackOption.update({ img: url })
      ctx.body = { url }
    } else {
      ctx.throw(415, '不支持该类型格式的图片')
    }
  }
  async checkOptionExist(ctx, next) { //检查选项是否存在
    const id = ctx.params.id
    const option = await bookBack.findById(id)
    if (option) {
      ctx.state.bookBackOption = option
      await next()
    } else {
      ctx.throw(404, '该选项不存在')
    }
  }
  async delete(ctx) {
    // const paths = path.join(__dirname, '../public/uploads', '/book/back')
    // console.log(paths)
    const id = ctx.params.id
    await bookBack.findByIdAndRemove(id)
    ctx.status = 204
  }
  async bookUpload(ctx) { // 书籍上传
    ctx.verifyParams({
      name: { type: 'string', required: true },
      introduction: { type: 'string', required: true },
    })
    const files = ctx.request.files
    const {name, introduction} = ctx.request.body
    if (files.file.size == 0) {
      ctx.throw(415, '上传文件不能为空') 
    } else {
      for (const value of bookUploadFileType) {
        if (files.file.type.includes(value)) {
          const paths = path.join(__dirname, '../public/uploads', '/book')
          const baseName = path.basename(files.file.path)
          const filePath = path.resolve(paths+'/file', `./${baseName}.${value}`)
          const readStream = fs.createReadStream(files.file.path)
          const writeStream = fs.createWriteStream(filePath)
          readStream.pipe(writeStream)
          const fileUrl = `${ctx.origin}/uploads/book/file/${baseName}.${value}`
          if (files.img.size != 0) {
            const imgSuffix =  files.img.type.match(/\/(.*)/ig)[0].replace('/','')
            const baseName = path.basename(files.img.path)
            const imgPath = path.resolve(paths+'/img', `./${baseName}.${imgSuffix}`)
            const readStream = fs.createReadStream(files.img.path)
            const writeStream = fs.createWriteStream(imgPath)
            readStream.pipe(writeStream)
            const imgUrl = `${ctx.origin}/uploads/book/img/${baseName}.${imgSuffix}`
            await new bookFile({
              file: fileUrl,
              img: imgUrl,
              name,
              user: ctx.state.user._id,
              introduction,
            }).save()
            ctx.status = 200
            return 0
          }
          await new bookFile({
            file: fileUrl,
            name,
            user: ctx.state.user._id,
            introduction,
          }).save()
          ctx.status = 200
          return 0
        }
      }
      ctx.throw(415, '上传文件类型错误，规定为：'+bookUploadFileType.join('，'))
    }
  }
  async bookList(ctx) { //书籍列表
    let { fields = '', page = 1, perPage = 15 } = ctx.query
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    page = Math.max(page * 1, 1) - 1
    perPage = Math.max(perPage * 1, 1)
    ctx.body = await bookFile.find().select(selectFields).populate('user').limit(perPage).skip(perPage * page)
  }
}

module.exports = new BackCtl
